import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { MatPaginator, MatPaginatorIntl, PageEvent } from '@angular/material';

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/distinctUntilChanged';

import { BlogService } from '../../blog.service';

@Component({
  selector: 'app-what-is-new',
  templateUrl: './what-is-new.component.html',
  styleUrls: ['./what-is-new.component.scss']
})
export class WhatIsNewComponent implements OnInit {
  repo: any;
  issues: Observable<any[]>;
  length;
  pageSize = 7;
  pageSizeOptions = [7];

  private searchIssues = new Subject<PageEvent>();
  pageEvent: PageEvent;

  constructor(
    private matPaginatorIntl: MatPaginatorIntl,
    private blogService: BlogService
  ) { }

  ngOnInit() {
    this.matPaginatorIntl.itemsPerPageLabel = "每页条数：";
    this.matPaginatorIntl.nextPageLabel = "";
    this.matPaginatorIntl.previousPageLabel = "";
    this.matPaginatorIntl.getRangeLabel = (page: number, pageSize: number, length: number) => { if (length == 0 || pageSize == 0) { return `0 of ${length}`; } length = Math.max(length, 0); const startIndex = page * pageSize;
      const endIndex = startIndex < length ? Math.min(startIndex + pageSize, length) : startIndex + pageSize; return `${startIndex + 1} - ${endIndex} / ${length}`; }
    this.blogService.getRepo()
     .subscribe(repo => this.length = repo.open_issues_count);

    this.issues = this.matPaginatorIntl.changes
      .switchMap(() => this.pageEvent
        ? this.blogService.getIssues(this.pageEvent.pageIndex + 1, this.pageEvent.pageSize)
        : this.blogService.getIssues(1, this.pageSize));
  }

  ngAfterViewInit() {
    this.search();
  }

  search(): void {
    this.matPaginatorIntl.changes.next();
  }
}
